﻿using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Search;
using AjaxSearch.Entities;
using System.Linq;
using DotNetNuke.Common;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;

namespace AjaxSearch.Services
{
    /// <summary>
    /// Summary description for SearchService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [ScriptService]
    public class SearchService : System.Web.Services.WebService
    {

        /// <summary>
        /// Gets the search results.
        /// </summary>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        [WebMethod]
        public List<CustomSearchItemResult> GetSearchResults(string criteria)
        {
            
            List<CustomSearchItemResult> foundItems = new List<CustomSearchItemResult>();
            int portalID = PortalController.GetCurrentPortalSettings().PortalId;

            FileController fileController = new FileController();
            ModuleController moduleController = new ModuleController();

            SearchResultsInfoCollection resultCollection =
                SearchDataStoreProvider.Instance().GetSearchResults(portalID, criteria);


            foundItems = (
                from SearchResultsInfo searchResultsInfo in resultCollection
                select new CustomSearchItemResult
                {
                    Author = searchResultsInfo.Author,
                    AuthorName = searchResultsInfo.AuthorName,
                    Description = searchResultsInfo.Description,
                    ImageUrl = (searchResultsInfo.Image.Equals(0) || searchResultsInfo.Image.Equals(-1)) ? System.Web.VirtualPathUtility.ToAbsolute("~/DesktopModules/AjaxSearch/Img/not_found.png")
                    : fileController.GetFileById(searchResultsInfo.Image, portalID).RelativePath,
                    ModuleName = moduleController.GetModule(searchResultsInfo.ModuleId).DesktopModule.FriendlyName,
                    Title = searchResultsInfo.Title,
                    PublicationDate = searchResultsInfo.PubDate,
                    Url = Globals.NavigateURL(searchResultsInfo.TabId)
                }
            ).ToList();

            return foundItems;

        }
    }
}
